import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_test1/api/http/http_request.dart';
import 'package:flutter_test1/constant/Constant.dart';
import 'package:flutter_test1/preference/PreferencesManager.dart';
import 'package:flutter_test1/views/home/home.dart';
import 'package:flutter_test1/views/mine/mine.dart';

class MainPage extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    return _MainPage();
  }
}

class _MainPage extends State<MainPage>{
  final List<String> swiper_images = ["assets/images/home_banner1.png","assets/images/home_banner1.png"];
  int selectedIndex = 0;
  final List<Widget> list_widget = [HomeWidget(),MineWidget()];
  DateTime _lastPressedAt = DateTime.now(); //上次点击时间

  @override
  Widget build(BuildContext context) {
    return new WillPopScope(
      child: new Scaffold(
        appBar: PreferredSize(
          preferredSize: Size.fromHeight(MediaQueryData.fromWindow(window).padding.top),
          child: SafeArea(
            top: true,
            child: Offstage(),
          ),
        ),
        floatingActionButton: FloatingActionButton(onPressed: (){
          PreferencesManager.getInstance().putBoolean(Constants.ISLOGIN, false);
          SRHttpRequest.getInstance().requestManager.jumpToLogin(context);
        },child: Icon(Icons.exit_to_app)),
        floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
        bottomNavigationBar: BottomAppBar(
          color: Colors.white,
          shape: CircularNotchedRectangle(),
          child: Row(
            children: [
              IconButton(onPressed: (){
                bottomItemTap(0);
              }, icon: Icon(Icons.home)),
              SizedBox(),
              IconButton(onPressed: (){
                bottomItemTap(1);
              }, icon: Icon(Icons.android)),
            ],
            mainAxisAlignment: MainAxisAlignment.spaceAround,
          ),
        ),
        body: IndexedStack(
          index: selectedIndex,
          children: list_widget,
        ),
      ),
      onWillPop: () async {
        print('点击返回');
        if (_lastPressedAt == null || DateTime.now().difference(_lastPressedAt) > Duration(seconds: 1)) {
          print('不退出');
          //两次点击间隔超过1秒则重新计时
          _lastPressedAt = DateTime.now();
          EasyLoading.showToast("再点一次返回退出");
          return false;
        }else{
          print('退出');
          return true;
        }
      }
    );
  }

  void bottomItemTap(int index){
    if(index != selectedIndex){
      setState(() {
        selectedIndex = index;
      });
    }
  }
}